package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.letv.whatslive.common.utils.Constants;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Employee;
import com.letv.whatslive.model.Menu;
import com.letv.whatslive.model.User;
import com.letv.whatslive.model.WeidianItem;
import com.letv.whatslive.model.convert.EmployeeConvert;
import com.letv.whatslive.model.convert.MenuConvert;
import com.letv.whatslive.model.convert.UserConvert;
import com.letv.whatslive.model.convert.WeidianItemConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by wangjian7 on 2016/9/20.
 */
@Repository
public class WeidianItemDAO extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(WeiDianTokenInfoDAO.class);

    protected String collectionName = "weidianItem";


    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);

    }

    /*  public Map<Long ,User> getUsersByIds(List<Long> idList){
          Map<Long ,User> users = new HashMap<Long, User>();
          BasicDBList values = new BasicDBList();
          for (Long id : idList) {
              values.add(id);
          }
          BasicDBObject queryCondition = new BasicDBObject();
          queryCondition.put("_id", new BasicDBObject("$in", values));
          DBCursor cur = this.dbCollection.find(queryCondition);
          while (cur.hasNext()) {
              DBObject dbObject = cur.next();
              User user = UserConvert.castDBObjectToUser(dbObject);
              setValueToUser(user);
              users.put(user.getUserId(), user);
          }
          return users;
      }*/


    public Map<String, WeidianItem> batchFindItems(List<String> params) {
        Map<String, WeidianItem> result = new HashMap<String, WeidianItem>();
        BasicDBObject query = new BasicDBObject();
        BasicDBList values = new BasicDBList();
        try {
            if (params != null && params.size() > 0) {
                for (String param : params) {
                    values.add(param);
                }
                query.put("itemid", new BasicDBObject("$in", values));

            }
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianItem weidianItem = WeidianItemConvert.castDBObjectToWeidianItem(dbObject);
                weidianItem.setUrl(Constants.WEIDIAN_ITEM_URL + weidianItem.getItemid());
                if (weidianItem.getImgs() != null && weidianItem.getImgs().size() > 0) {
                    weidianItem.setPic(weidianItem.getImgs().get(0));
                }
                if (weidianItem.getThumb_imgs() != null && weidianItem.getThumb_imgs().size() > 0) {
                    weidianItem.setPic_thumb(weidianItem.getThumb_imgs().get(0));
                }
                result.put(weidianItem.getItemid(), weidianItem);
            }
        } catch (Exception e) {
            logger.error("getWeidianItemListByParams error!", e);
        }
        return result;
    }

    /**
     * 根据id查询商品
     *
     * @param id
     * @return
     */
    public WeidianItem getWeidianItemById(Long id) {
        DBObject dbObject = new BasicDBObject();
        dbObject.put("_id", id);
        DBObject result = dbCollection.findOne(dbObject);
        if (result == null) {
            return null;
        }
        WeidianItem weidianItem = WeidianItemConvert.castDBObjectToWeidianItem(result);
        return weidianItem;
    }

    /**
     * 修改商品
     *
     * @param weidianItem
     */
    public void updateWeidianItem(WeidianItem weidianItem) {
        DBObject queryCondition = new BasicDBObject();
        Long weidianItemId = weidianItem.getId();
        queryCondition.put("_id", weidianItemId); // 用来确定要修改的文档
        DBObject setValue = WeidianItemConvert.castWeidianItemToDBObject(weidianItem);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    public void insertItems(List<WeidianItem> weidianItemList) {
        if (weidianItemList != null && weidianItemList.size() > 0) {
            List<DBObject> dbList = Lists.newArrayList();
            Long createTime = System.currentTimeMillis();
            for (WeidianItem item : weidianItemList) {
                item.setCreateTime(createTime);
                DBObject dbObject = WeidianItemConvert.castWeidianItemToDBObject(item);
                dbList.add(dbObject);
            }
            this.multiInsert(dbList);
        }

    }

    public void updateItems(List<WeidianItem> weidianItemList) {
        if (weidianItemList != null && weidianItemList.size() > 0) {
            List<DBObject> dbList = Lists.newArrayList();
            Long updateTime = System.currentTimeMillis();
            for (WeidianItem item : weidianItemList) {
                item.setUpdateTime(updateTime);
                DBObject queryCondition = new BasicDBObject();
                queryCondition.put("_id", item.getId()); // 用来确定要修改的文档
                DBObject setValue = WeidianItemConvert.castWeidianItemToDBObject(item);
                //剔除主键修改
                if (setValue.containsKey("_id")) {
                    setValue.removeField("_id");
                }
                DBObject values = new BasicDBObject("$set", setValue);
                this.dbCollection.update(queryCondition, values, false, false);
            }
        }

    }

    /**
     * 查询微店商品的记录数
     *
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countWeidianItemByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    public List<WeidianItem> getWeidianItemListByParams(Integer start, Integer limit, Map<String, Object> params) {
        List<WeidianItem> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBObject order = new BasicDBObject();
            order.put("createTime", -1);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianItem weidianItem = WeidianItemConvert.castDBObjectToWeidianItem(dbObject);
                weidianItem.setUrl(Constants.WEIDIAN_ITEM_URL + weidianItem.getItemid());
                if (weidianItem.getImgs() != null && weidianItem.getImgs().size() > 0) {
                    weidianItem.setPic(weidianItem.getImgs().get(0));
                }
                if (weidianItem.getThumb_imgs() != null && weidianItem.getThumb_imgs().size() > 0) {
                    weidianItem.setPic_thumb(weidianItem.getThumb_imgs().get(0));
                }
                result.add(weidianItem);
            }
        } catch (Exception e) {
            logger.error("getWeidianItemListByParams error!", e);
        }
        return result;
    }

    public List<WeidianItem> getAllWeidianItemListByParams(Map<String, Object> params) {
        List<WeidianItem> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBObject order = new BasicDBObject();
            order.put("createTime", -1);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianItem weidianItem = WeidianItemConvert.castDBObjectToWeidianItem(dbObject);
                weidianItem.setUrl(Constants.WEIDIAN_ITEM_URL + weidianItem.getItemid());
                if (weidianItem.getImgs() != null && weidianItem.getImgs().size() > 0) {
                    weidianItem.setPic(weidianItem.getImgs().get(0));
                }
                if (weidianItem.getThumb_imgs() != null && weidianItem.getThumb_imgs().size() > 0) {
                    weidianItem.setPic_thumb(weidianItem.getThumb_imgs().get(0));
                }
                result.add(weidianItem);
            }
        } catch (Exception e) {
            logger.error("getAllWeidianItemListByParams error!", e);
        }
        return result;
    }

    public Map<String, WeidianItem> getAllWeidianItemMapInOneShop(String sellerId) {
        Map<String, WeidianItem> result = Maps.newHashMap();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = new BasicDBObject();
            query.put("seller_id", sellerId);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianItem weidianItem = WeidianItemConvert.castDBObjectToWeidianItem(dbObject);
                weidianItem.setUrl(Constants.WEIDIAN_ITEM_URL + weidianItem.getItemid());
                if (weidianItem.getImgs() != null && weidianItem.getImgs().size() > 0) {
                    weidianItem.setPic(weidianItem.getImgs().get(0));
                }
                if (weidianItem.getThumb_imgs() != null && weidianItem.getThumb_imgs().size() > 0) {
                    weidianItem.setPic_thumb(weidianItem.getThumb_imgs().get(0));
                }
                result.put(weidianItem.getItemid(), weidianItem);
            }
        } catch (Exception e) {
            logger.error("getAllWeidianItemListByParams error!", e);
        }
        return result;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     *
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params) {
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("openId") != null) {
                query.put("seller_id", ObjectUtils.toString(params.get("openId")));
            }
            if (params.get("item_name_regex") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("item_name_regex") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("item_name", pattern);
            }
            if (params.get("online") != null) {
                query.put("online", ObjectUtils.toInteger(params.get("online")));
            }
        }
        return query;
    }
}